import os
import urllib

from google.appengine.api import users
from google.appengine.ext import ndb

import jinja2
import webapp2

JINJA_ENVIRONMENT = jinja2.Environment(
    loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),
    extensions=['jinja2.ext.autoescape'],
    autoescape=True)

DEFAULT_FAMILY_NAME = 'default_family'


# We set a parent key on the 'Tasks' to ensure that they are all in the same
# entity group. Queries across the single entity group will be consistent.
# However, the write rate should be limited to ~1/second.

def family_key(family_name=DEFAULT_FAMILY_NAME):
    """Constructs a Datastore key for a Family entity with family_name."""
    return ndb.Key('Family', family_name)


# Models an individual task
class Task(ndb.Model):
    # The task creator
    author = ndb.UserProperty(required=True)

    # The assignee, can be assigned later
    assignee = ndb.UserProperty()

    # A short description of the task
    brief = ndb.StringProperty(required=True, indexed=False)

    # The date the task was created.
    # Stored in database with a shorter name.
    creation_date = ndb.DateTimeProperty('cdate', required=True, auto_now_add=True)

    # The date the task is due.
    # Stored in database with a shorter name.
    due_date = ndb.DateTimeProperty('ddate', auto_now_add=True)

    # Whether or not the task has been completed
    done = ndb.BooleanProperty(required=True, indexed=False)

    # The number of points the task is worth
    points = ndb.StringProperty(required=True, indexed=False)

    # Queries all tasks in the given family.
    @classmethod
    def query_task(cls, ancestor_key):
        return cls.query(ancestor=ancestor_key).order(-cls.creation_date)


class MainPage(webapp2.RequestHandler):

    def get(self):
        family_name = self.request.get('family_name',
                                       DEFAULT_FAMILY_NAME)
        tasks = Task.query_task((family_key(family_name))).fetch(10)

        if users.get_current_user():
            url = users.create_logout_url(self.request.uri)
            url_linktext = 'Logout'
        else:
            url = users.create_login_url(self.request.uri)
            url_linktext = 'Login'

        template_values = {
            'tasks': tasks,
            'family_name': urllib.quote_plus(family_name),
            'url': url,
            'url_linktext': url_linktext,
        }

        template = JINJA_ENVIRONMENT.get_template('index.html')
        self.response.write(template.render(template_values))


class Tasklist(webapp2.RequestHandler):

    def post(self):
        # We set the same parent key on the 'Task' to ensure each Task
        # is in the same entity group. Queries across the single entity group
        # will be consistent. However, the write rate to a single entity group
        # should be limited to ~1/second.
        family_name = self.request.get('family_name',
                                        DEFAULT_FAMILY_NAME)
        task = Task(parent=family_key(family_name))

        if users.get_current_user():
            task.author = users.get_current_user()

        task.points = "10"

        task.brief = self.request.get('brief')

        task.done = False

        # Store the newly created task into the system
        task.put()

        query_params = {'family_name': family_name}
        self.redirect('/?' + urllib.urlencode(query_params))


# Register URLs with the class responsible for handling it.
# debug=True allows the application to put debug information in the browser.
application = webapp2.WSGIApplication([
    ('/', MainPage),
    ('/create', Tasklist),
], debug=True)
